from absl import app, flags

import os
from selenium import webdriver
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities


def create_driver(job_type):
  caps = DesiredCapabilities.CHROME

  options = webdriver.ChromeOptions()

  prefs = {
      'profile.default_content_setting_values': {
          'cookies': 2,
          'images': 2,
          'plugins': 2,
          'popups': 2,
          'geolocation': 2,
          'notifications': 2,
          'auto_select_certificate': 2,
          'fullscreen': 2,
          'mouselock': 2,
          'mixed_script': 2,
          'media_stream': 2,
          'media_stream_mic': 2,
          'media_stream_camera': 2,
          'protocol_handlers': 2,
          'ppapi_broker': 2,
          'automatic_downloads': 2,
          'midi_sysex': 2,
          'push_messaging': 2,
          'ssl_cert_decisions': 2,
          'metro_switch_to_desktop': 2,
          'protected_media_identifier': 2,
          'app_banner': 2,
          'site_engagement': 2,
          'durable_storage': 2
      }
  }
  options.add_experimental_option('prefs', prefs)
  options.add_argument("start-maximized")
  options.add_argument("disable-infobars")
  options.add_argument("--disable-extensions")
  options.add_argument('--headless')
  driver = webdriver.Chrome('chromedriver', desired_capabilities=caps, chrome_options=options)
  driver.implicitly_wait(0.1)
  driver.get(f'http://jenkins-hft.corp.prestolabs.io/job/{job_type}')
  driver.find_element_by_id("j_username").send_keys(flags.FLAGS.username)
  driver.find_element_by_name("j_password").send_keys(flags.FLAGS.password)
  driver.find_element_by_class_name("submit-button").click()
  return driver


def crawl_jenkins_log(driver, job_type, log_number):
  driver.get(
      f'http://jenkins-hft.corp.prestolabs.io/job/{job_type}/{log_number}/timestamps/?time=yyyyMMdd:HH:mm:ss&appendLog&locale=en'
  )
  pgsrc = driver.page_source
  return pgsrc


def get_last_build_number(driver, job_type):
  driver.get(f'http://jenkins-hft.corp.prestolabs.io/job/{job_type}/lastStableBuild/buildNumber')
  return int(driver.find_element_by_tag_name('body').text)


def download_a_log(driver, job_type, downdir, log_number):
  pagesrc = crawl_jenkins_log(driver, job_type, log_number)
  downfile = f'{downdir}/{job_type}_{log_number}.txt'
  with open(downfile, 'w') as outfile:
    print(pagesrc, file=outfile)


def main(_):
  assert flags.FLAGS.username is not None
  assert flags.FLAGS.password is not None
  downdir = "download"
  if not os.path.exists(downdir):
    os.makedirs(downdir)

  for job_type in ["aliyun-instance-watcher", "aws-instance-watcher"]:
    driver = create_driver(job_type)
    last_build_number = get_last_build_number(driver, job_type)
    for log_number in range(last_build_number - flags.FLAGS.num_history, last_build_number, 1):
      download_a_log(driver, job_type, downdir, log_number)
    driver.close()
    driver.quit()


if __name__ == "__main__":
  flags.DEFINE_string('username', None, '')
  flags.DEFINE_string('password', None, '')
  flags.DEFINE_integer('num_history', 400, '')
  app.run(main)
